package fnsvr

import "sync"

// NamedMutex 是一个基于名称的互斥锁管理器
type NamedMutex struct {
	mu    sync.Mutex
	locks map[string]*lockWithCount
}

// lockWithCount 用于跟踪锁和其引用计数
type lockWithCount struct {
	mutex    *sync.Mutex
	refCount int
}

// NewNamedMutex 创建一个新的 NamedMutex 实例
func NewNamedMutex() *NamedMutex {
	return &NamedMutex{
		locks: make(map[string]*lockWithCount),
	}
}

// Lock 根据名称获取锁并锁定
func (nm *NamedMutex) Lock(name string) {
	nm.mu.Lock()
	if _, exists := nm.locks[name]; !exists {
		nm.locks[name] = &lockWithCount{
			mutex:    &sync.Mutex{},
			refCount: 0,
		}
	}
	lock := nm.locks[name]
	lock.refCount++
	nm.mu.Unlock()

	lock.mutex.Lock()
}

// Unlock 根据名称解锁
func (nm *NamedMutex) Unlock(name string) {
	nm.mu.Lock()
	if lock, exists := nm.locks[name]; exists {
		lock.refCount--
		lock.mutex.Unlock()
		if lock.refCount <= 0 {
			delete(nm.locks, name)
		}
	}
	nm.mu.Unlock()
}
